package job

import (
	task "Monitor/task"
	"fmt"
	"os/exec"
	"strconv"
	"strings"

	"github.com/gogf/gf/os/gcfg"
	"github.com/gogf/gf/os/gcron"
	"github.com/gogf/gf/os/glog"
	"github.com/sparrc/go-ping"
)

func Ping(req *task.TaskRequest, resp *task.TaskResponse) {
	pinger, err := ping.NewPinger(req.RequestCallParams.CommString)
	if pinger == nil || err != nil {
		req.Reply.TaskErr(err)
	} else {
		glog.Println(pinger.Addr())
		pinger.SetPrivileged(true)
		pinger.Count = 5
		pinger.OnRecv = func(pkt *ping.Packet) {
			fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
				pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
		}
		pinger.OnFinish = func(stats *ping.Statistics) {
			fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
			fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
				stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
			fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
				stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
		}
		pinger.Run() // blocks until finished
		glog.Println(req.RequestCallParams.CommString)
	}

}

func WinPing(req *task.TaskRequest, resp *task.TaskResponse) {
	var ping_count [3]int
	var ping_host string = req.RequestCallParams.CommString
	cmd := exec.Command("ping", "-n", "5", ping_host)
	cmdOutput, err := cmd.CombinedOutput()
	if err != nil {
		req.Reply.TaskErr(err)
	}
	out_slice := strings.Split(string(cmdOutput), "\r\n")
	//取最后一行
	new_string := strings.Join(out_slice[len(out_slice)-2:len(out_slice)-1], "")
	out_replace := strings.Replace(new_string, " ", "", -1)
	new_slice := strings.Split(out_replace, "=")[1:]
	for i := 0; i < len(new_slice); i++ {
		//fmt.Printf("%q\n", strings.Split(new_slice[i], "ms")[0])
		ping_res := strings.Split(new_slice[i], "ms")[0]
		ping_time, err := strconv.Atoi(ping_res)
		if err != nil {
			req.Reply.TaskErr(err)
		}
		ping_count[i] = ping_time
	}
	taskResult := make(map[string]string)
	taskResult["ping_max_"+ping_host] = strconv.Itoa(ping_count[0])
	taskResult["ping_avg_"+ping_host] = strconv.Itoa(ping_count[1])
	taskResult["ping_min_"+ping_host] = strconv.Itoa(ping_count[2])
	JobLogger.Debug("%s %v", ping_host, taskResult)
	req.Reply.TaskDone(taskResult)
}

func PingRun() {
	hosts := gcfg.Instance().GetJsons("ping_task")
	for i := 0; i < len(hosts); i++ {
		cronString := hosts[i].GetString("cron")
		ping_host := hosts[i].GetString("host")
		ping_name := hosts[i].GetString("name")
		c := NewCron(cronString, nil, ping_name)
		err := c.AddCron()
		if err != nil {
			JobLogger.Error("cron entry err [%s]", err)
			return
		}
		c.SetReplyTask()
		c.SetTaskParams(ping_host)
		c.SetCallTask(WinPing)
		gcron.Start(c.Name)
	}
}
